<?php

class OrdersController extends AppController {

    var $name = 'Orders';
    var $uses = array('Product', 'Cart', 'Order', 'Paymentmethod', 'AddressBook', 'AddressBookField', 'User');
    var $components = array('Session', 'Email');
    var $helpers = array('Html', 'Form');

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allowedActions = array('incoming_ipn', 'curl_process', 'fsockopen_process', 'emailuser', 'create_order', 'update_order');
    }

    /** ----------------------------------------
      /**  Process an Incoming IPN From PayPal
      /** ---------------------------------------- */
    function incoming_ipn() {
        $this->layout = false;
        $this->autoRender = false;
        if (empty($_POST)) {
            @header("HTTP/1.0 404 Not Found");
            @header("HTTP/1.1 404 Not Found");
            exit('No Data Sent');
        }

        $url = (!function_exists('openssl_open')) ? 'http://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.sandbox.paypal.com/cgi-bin/webscr';
        //$url = ( ! function_exists('openssl_open')) ? 'http://www.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr';

        /** ----------------------------------------
          /**  Ping Them Back For Confirmation
          /** ---------------------------------------- */
        if (function_exists('curl_init')) {
            $result = $this->curl_process($url);
        } else {
            $result = $this->fsockopen_process($url);
        }

        if (stristr($result, 'VERIFIED')) {
            if ($_POST['payment_status'] == "Pending") {
                $this->create_order($_POST);
            }
            if ($_POST['payment_status'] == "Completed") {
                $this->update_order($_POST);
            }
        } elseif (stristr($result, 'INVALID')) {
            // Error Checking?
            @header("HTTP/1.0 200 OK");
            @header("HTTP/1.1 200 OK");
            exit('Invalid');
        }
    }

    function curl_process($url) {
        $postdata = 'cmd=_notify-validate';

        foreach ($_POST as $key => $value) {
            // str_replace("\n", "\r\n", $value)
            // put line feeds back to CR+LF as that's how PayPal sends them out
            // otherwise multi-line data will be rejected as INVALID
            $postdata .= "&$key=" . urlencode(stripslashes(str_replace("\n", "\r\n", $value)));
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

        // Start ob to prevent curl_exec from displaying stuff. 
        ob_start();
        curl_exec($ch);

        //Get contents of output buffer 
        $info = ob_get_contents();
        curl_close($ch);

        //End ob and erase contents.  
        ob_end_clean();

        return $info;
    }

    function fsockopen_process($url) {
        $parts = parse_url($url);
        $host = $parts['host'];
        $path = (!isset($parts['path'])) ? '/' : $parts['path'];
        $port = ($parts['scheme'] == "https") ? '443' : '80';
        $ssl = ($parts['scheme'] == "https") ? 'ssl://' : '';
        if (isset($parts['query']) && $parts['query'] != '') {
            $path .= '?' . $parts['query'];
        }
        $postdata = 'cmd=_notify-validate';
        foreach ($_POST as $key => $value) {
            // str_replace("\n", "\r\n", $value)
            // put line feeds back to CR+LF as that's how PayPal sends them out
            // otherwise multi-line data will be rejected as INVALID
            $postdata .= "&$key=" . urlencode(stripslashes(str_replace("\n", "\r\n", $value)));
        }
        $info = '';
        $fp = @fsockopen($ssl . $host, $port, $error_num, $error_str, 8);
        if (is_resource($fp)) {
            fputs($fp, "POST {$path} HTTP/1.0\r\n");
            fputs($fp, "Host: {$host}\r\n");
            fputs($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
            fputs($fp, "Content-Length: " . strlen($postdata) . "\r\n");
            fputs($fp, "Connection: close\r\n\r\n");
            fputs($fp, $postdata . "\r\n\r\n");
            while ($datum = fread($fp, 4096)) {
                $info .= $datum;
            }

            @fclose($fp);
        }
        return $info;
    }

    function create_order($POST) {
        $product_cost = 0;
        $cart_ids = explode("|", $POST['custom']);
        if ($cart_ids[0] == "AAFEE") {
            $datas['Invoice']['id'] = $cart_ids[1];
            $datas['Invoice']['transaction_id'] = $POST['txn_id'];
            $datas['Invoice']['pay_date'] = date("Y-m-d H:i:s");
            $this->Invoice->save($datas['Invoice']);
            $this->emailuser($POST, '0');
        } else {
            foreach ($cart_ids as $cart_id) {
                if ($cart_id > 0) {
                    $carts = $this->Cart->find("first", array("conditions" => array("Cart.id" => $cart_id)));
                    $seller_id = $carts['Cart']['seller_id'];
                    $product_cost = $product_cost + ($carts['Cart']['product_cost'] * $carts['Cart']['quantity']);
                }
            }
            $Order['product_cost'] = $product_cost;
            $Order['shipping_cost'] = $POST['mc_gross_' . $POST['num_cart_items']];
            $Order['payment_status'] = $POST['payment_status'];
            $Order['seller_id'] = $seller_id;
            $Order['transaction_id'] = $POST['txn_id'];
            $Order['add_date'] = date("Y-m-d H:i:s");
            $Order['order_details'] = serialize($POST);
            $this->Order->save($Order);
            $order_id = $this->Order->getlastinsertid();
            if ($order_id > 0) {
                foreach ($cart_ids as $cart_id) {
                    if ($cart_id > 0) {
                        $Cart['id'] = $cart_id;
                        $Cart['order_id'] = $order_id;
                        if ($this->Cart->save($Cart)) {
                            $this->emailuser($POST, '0');
                        }
                    }
                }
            }
        }
    }

    function update_order($POST) {
        $cart_ids = explode("|", $POST['custom']);
        if ($cart_ids[0] == "AAFEE") {
            $datas['Invoice']['id'] = $cart_ids[1];
            $datas['Invoice']['transaction_id'] = $POST['txn_id'];
            $datas['Invoice']['invoice_status'] = "Paid Invoices";
            $this->Invoice->save($datas['Invoice']);
            $this->emailuser($POST, '1');
        } else {
            $orders = $this->Order->find("first", array("conditions" => array("Order.transaction_id" => $POST['txn_id']), "fields" => array('Order.id')));
            if ($orders['Order']['id'] > 0) {
                foreach ($cart_ids as $cart_id) {
                    if ($cart_id > 0) {
                        $Cart['id'] = $cart_id;
                        $Cart['payment_status'] = 1;
                        $this->Cart->save($Cart);
                        $carts = $this->Cart->find("first", array("conditions" => array("Cart.id" => $Cart['id'])));
                        $this->Product->query("UPDATE authentic_products SET product_totalsell=product_totalsell+" . $carts['Cart']['quantity'] . ",products_quantity=products_quantity-" . $carts['Cart']['quantity'] . " WHERE id='" . $carts['Cart']['product_id'] . "'");
                    }
                }
                $Order['id'] = $orders['Order']['id'];
                $Order['payment_status'] = "Complete";
                $Order['add_date'] = date("Y-m-d H:i:s");
                $Order['order_details'] = serialize($POST);
                if ($this->Order->save($Order)) {
                    $this->emailuser($POST, '1');
                }
            }
        }
    }

    function emailuser($options, $status=0) {
        $this->layout = null;
        $this->autoRender = false;
        $cart_ids = explode("|", $options['custom']);
        foreach ($cart_ids as $cart_id) {
            $cart = $this->Cart->find("first", array("conditions" => array("Cart.id" => $cart_id)));
        }
        $userinfo = $this->User->find("first", array("conditions" => array("User.id" => $cart['Cart']['user_id'])));

        $this->Email->to = $userinfo['User']['username'] . ' < ' . $userinfo['User']['email'] . ' >';
        //$this->Email->to = 'Sahbaj Uddin <sahbajuddin@yahoo.com>';
        $this->Email->subject = 'Authentic Avenue: New Order # ' . $cart['Cart']['order_id'];
        $this->Email->from = 'authenticavenue.com < noreply@authenticavenue.com >';
        $this->Email->template = 'order_invoice';
        $this->Email->sendAs = 'html';
        $this->set('userinfo', $userinfo);
        $this->set('status', $status);
        $this->set('orders', $options);
        $this->set('order_date', $cart['Cart']['add_date']);
        $this->Email->send();
    }

}

?>